import React from 'react';
import { Link } from 'react-router';

class Sort extends React.Component {
    constructor(props) {
        super(props);
        this.displayName = 'Sort';

        this.tableTitleChoices = {
            athlete: [ "排名","姓名","俱乐部","进球" ],
            club: [ "排名","俱乐部","积分" ],
            clubAthlete: [ "排名","姓名","进球" ],
        };

        this.state = {
            mode: props.mode,  // 必须是 this.tableTitleChoices 的 key
            is_highlight_topn: props.sortColor,
            unit: props.unit ? props.unit: '分',
            tableTitle: this.tableTitleChoices[props.mode],
            datas: props.data,
        }
    }

    highlight_topn () {
        if( this.state.is_highlight_topn ) {
            $("ul.sortList .rank:eq(0)").css("color","#f82169");
            $("ul.sortList .rank:eq(1)").css("color","#17b4ee");
            $("ul.sortList .rank:eq(2)").css("color","#23b359");
        }else{
            $("ul.sortList .rank").css("color","#8e8e93");
        };
    }

    componentDidMount() {
      this.highlight_topn();
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            is_highlight_topn: nextProps.sortColor,
            datas: nextProps.data,
        });
    }

    componentDidUpdate(prevProps, prevState) {
        this.highlight_topn();
    }

    render() {
        let tableTitleRendered = this.state.tableTitle.map(function(title, index){
            return (
                <span key={index} className={index==0?"":"wrap-item"}>{title}</span>
            );
        });

        let datasList = this.state.datas.map(function( data, index ) {
            let linkUrl = `${data.id}`;
            return (
              <li key={index} data-usr-id = {data.id}>
                  <Link to={linkUrl}>
                      <span className="rank">{data.rank}</span>
                      <p className="athDetail">
                          <span>
                              <img src={data.img} />
                              {data.name}
                          </span>
                          <span> {data.club} </span>
                          <span> <em>{data.score}</em>{this.state.unit}</span>
                      </p>
                  </Link>
              </li>
            )
        }.bind(this))

        return (
            <section className="sort">
                <div className={this.state.mode}>
                    <p className="tableTitle">
                        {tableTitleRendered}
                    </p>
                    <ul className="sortList">
                        {datasList}
                    </ul>
                </div>
            </section>
        );
    }
}

export default Sort;
